package com.jsn.hello_cmake

import android.content.Context
import android.content.Intent
import android.content.res.AssetManager
import android.graphics.*
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.SurfaceHolder
import android.widget.Toast
import com.jsn.sdklib.toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : AppCompatActivity() {

    lateinit var context:Context

    val coroutineScope= CoroutineScope(Dispatchers.Main)

    var isRunning:Boolean=true

    lateinit var bitmap :Bitmap

    init{

    }

    fun decodeSampledBitmapFromAsesetsCat(
        reqWidth: Int,
        reqHeight: Int
    ): Bitmap? {
        // First decode with inJustDecodeBounds=true to check dimensions
        return BitmapFactory.Options().run {

            inJustDecodeBounds = true

            BitmapFactory.decodeStream(assets.open("cat.jpg"),null,this)

            // Calculate inSampleSize
            inSampleSize = calculateInSampleSize(this, reqWidth, reqHeight)

            // Decode bitmap with inSampleSize set
            inJustDecodeBounds = false

            BitmapFactory.decodeStream(assets.open("cat.jpg"), null, this)
        }
    }

    fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
        // Raw height and width of image
        val (height: Int, width: Int) = options.run { outHeight to outWidth }
        var inSampleSize = 1

        if (height > reqHeight || width > reqWidth) {

            val halfHeight: Int = height / 2
            val halfWidth: Int = width / 2

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
                inSampleSize *= 2
            }
        }

        return inSampleSize
    }






    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context=this

        bitmap= decodeSampledBitmapFromAsesetsCat(100,100)!!

       sample_img.holder.addCallback(object : SurfaceHolder.Callback{
           override fun surfaceChanged(
               holder: SurfaceHolder?,
               format: Int,
               width: Int,
               height: Int
           ) {

           }

           override fun surfaceDestroyed(holder: SurfaceHolder?) {
               isRunning=false
           }

           override fun surfaceCreated(holder: SurfaceHolder?) {
              coroutineScope.launch(Dispatchers.Default) {
                  while(isRunning){
                      try {
                          //draw(sample_img.holder.lockCanvas())
                      }catch (e:Exception){
                          //ToastOnMain(e.message)
                      }finally {

                      }
                  }
              }
           }

       })


        Handler().postDelayed(Runnable {
            startActivity(Intent(this,AudioRecordActivity::class.java))
        },100)
    }

    suspend fun ToastOnMain(e:String?)= withContext(Dispatchers.Main){
        e?.run {
            context.toast(e)
        }

    }






    fun draw(canvas: Canvas){

        canvas?.apply {
            bitmap?.apply {
                canvas.drawBitmap(bitmap, Matrix(), Paint())
               /* canvas.drawARGB(java.util.Random().nextInt(255),
                    java.util.Random().nextInt(255),java.util.Random().nextInt(255),java.util.Random().nextInt(255))*/
                sample_img.holder.unlockCanvasAndPost(canvas)
            }

        }

    }



    companion object {




        // Used to load the 'native-lib' library on application startup.
        init {
            System.loadLibrary("native-lib")


        }
    }

    private suspend fun suspendingCropBitmap(bitmap: Bitmap, sliceX: Int, sliceY: Int) =
        withContext(Dispatchers.Default) {
            Bitmap.createBitmap(bitmap, 0, 0, bitmap.width / sliceX, bitmap.height / sliceY)
        }



    private suspend fun suspendLoadImage(map:Bitmap?) :Bitmap? =
        withContext(Dispatchers.IO) {
            val imgUrl = "http://oss.tuyuing.com/TUYU/trend/20190930/trend257401569854904487.jpeg"
            val connection = URL(imgUrl).openConnection() as HttpURLConnection
            if (connection.responseCode != 200) {
                return@withContext null
            }
            withContext(Dispatchers.Main){
                context.toast("ok")
            }
            return@withContext BitmapFactory.decodeStream(connection.inputStream)
        }
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    external fun stringFromJNI(): String


}
